import store from "@/public/store.js"

const requestSettings = (opt) => { // api参数处理, 请求前
	opt.header.token = store.state.uInfo.token || ''
	opt.url = store.state.baseUrl + opt.url
	
	return opt
}
const getSuccessInfo = async (response, data, resolve, reject) => { // 网络200后的数据判断， 请求后
	let res = response.data
	// console.log(response)
	if (res.code == 0) { // 成功请求
		// console.log(res.data)
		if(res.data) {
			if (res.data.code == -1) { // 成功后的未注册
				if(data.data.toBackPrev) {
					uni.navigateTo({
						url: `/subpages/login/login?back=${data.data.toBackPrev}`,
					})
				} else {
					uni.navigateTo({
						url: '/subpages/login/login'
					})
				}
				reject('error')
			}
		}
		// uni.hideLoading()
		resolve(response)
	} else if (res.code == -1) { // 错误
		uni.showToast({
			title: res.msg,
			icon: 'none',
			duration: 2000
		});
		reject('error')
	} else if (res.code == -999) { // 未登录
		let codeInfo = await uni.login()
		let query = {
			code: codeInfo[1].code,
		}
		if(data.data.toBackPrev) {
			query.toBackPrev = data.data.toBackPrev
		}
		// 静默登录
		request({
			url: '/webapp/login',
			method: 'POST',
			data: query
		}).then(result => {
			store.commit('setUserInfo', result.data.data.userinfo)
			uni.setStorageSync('uInfo', JSON.stringify(store.state.uInfo))
		}).then(() => {
			request({
				url: data.url,
				method: data.method,
				data: data.data
			}).then(function(backResult){
				resolve(backResult)
			})
		})
	} else {
		uni.showToast({ // 其他
			title: res.msg,
			icon: 'none',
			duration: 2000
		});
		uni.hideLoading()
		reject('error')
	}
}
const getFailInfo = (error) => { // 网络异常的数据判断
	uni.showToast({ // 网络异常
		title: '服务器连接失败！',
		icon: 'none',
		duration: 2000
	});
	uni.hideLoading()
	return error
}
const request = function(data) {
	return new Promise(function(resolve, reject) {
		uni.request(requestSettings({
			...data,
			header: {
				'Content-Type': 'application/json'
			},
			success: (res) => {
				getSuccessInfo(res, data, (res) => {
					resolve(res)
				}, (err) => {
					reject(err)
				})
			},
			fail: (err) => {
				reject(getFailInfo(err))
			}
		}))
	})
}
export default request
